package com.free.bsf.core.util;

import com.free.bsf.core.base.Callable;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * Copyright (c) 2019. 上海昌投网络科技有限公司.
 * All rights reserved.
 *
 * @author lanlan
 * @date 2021/4/6 0006 22:47
 */


public class BeanCopyUtil {

    /**
     * 对象属性拷贝
     * @param source 源对象
     * @param targetSupplier 生成目标对象的Supplier
     * @param <T2> 目标对象类型
     * @return 目标对象
     */
    public static <T1,T2> T2 copyProperties(T1 source, Supplier<T2> targetSupplier){
        return copyProperties(source,targetSupplier,null);
    }
    public static <T1,T2> T2 copyProperties(T1 source, Supplier<T2> targetSupplier, Callable.Action2<T1,T2> action2) {
        if (source == null || targetSupplier == null) {
            return null;
        }
        T2 target = targetSupplier.get();
        org.springframework.beans.BeanUtils.copyProperties(source, target);
        if(action2!=null){
            action2.invoke(source,target);
        }
        return target;
    }

    /**
     * 对象列表属性拷贝
     * @param sourceList 源对象列表
     * @param targetSupplier 生成目标对象的Supplier
     * @param <T2> 目标对象类型
     * @return 目标对象列表
     */
    public static <T1,T2> List<T2> copyPropertiesList(List<T1> sourceList, Supplier<T2> targetSupplier){
        return copyPropertiesList(sourceList,targetSupplier,null);
    }
    public static <T1,T2> List<T2> copyPropertiesList(List<T1> sourceList, Supplier<T2> targetSupplier, Callable.Action2<T1,T2> action2) {
        if (CollectionUtils.isEmpty(sourceList) || targetSupplier == null) {
            return Collections.emptyList();
        }
        return  sourceList.stream()
                .map(source -> copyProperties(source, targetSupplier,action2))
                .collect(Collectors.toList());
    }


}
